package org.alex.sample.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.alex.sample.VO.UserVO;
import org.alex.sample.model.ExamUserRole;
import org.alex.sample.model.Subject;
import org.alex.sample.model.User;
import org.alex.sample.page.PagerModel;
import org.alex.sample.service.SubjectService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class SubjectController {

	@Autowired
	private SubjectService subjectService;
	
	@Autowired
	private LocaleResolver localeResolver;
	
	@Autowired
	private MessageSource messageSource;
	
	//中英文切换
	@RequestMapping(value = "/subjectChangeLocale")
	public String subjectChangeLocale(HttpServletRequest request, HttpServletResponse response, String localeType){
		if("en_US".equals(localeType)){
			localeResolver.setLocale(request, response, Locale.US);
		}else if("zh_CN".equals(localeType)){
			localeResolver.setLocale(request, response, Locale.CHINA);
		}
		return "redirect:/subjects";
	}
	
	//查找全部
	@RequestMapping(value = "/subjects")
	public String subjects(Model model) throws Exception{
		PagerModel<Subject> subjectList = subjectService.findAllByPage();
		model.addAttribute("subjectList", subjectList);
		model.addAttribute("subject", new Subject());
		model.addAttribute("edit", messageSource.getMessage("page.index.edit", null, LocaleContextHolder.getLocale()));
		return "subject/subjectList";
	}
	
	//使用ajax添加
	@ResponseBody
	@RequestMapping(value = "/subjectAdd", method = RequestMethod.POST)
	public Map<String, Object> subjectAdd(@Validated Subject subject, BindingResult result) {
		Map<String, Object> messages = new HashMap<String, Object>();
		messages.put("success", false);
		if(result.hasErrors()) {
			return messages;
		}
		try {
			subjectService.createSubject(subject);
			messages.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return messages;
	}
	
	//使用ajax修改查找单条数据
	@ResponseBody
	@RequestMapping(value = "subjectEdit", method = RequestMethod.GET)
	public Map<String, String> subjectToEdit(Model model, @RequestParam Integer subId) throws Exception {
		Map<String, String> subjectMap = new HashMap<String, String>();
		Subject subject = subjectService.findSubjectById(subId);
		subjectMap.put("subId", String.valueOf(subject.getSubId()));
		subjectMap.put("name", subject.getName());
		subjectMap.put("description", subject.getDescription());
		subjectMap.put("testCount", String.valueOf(subject.getTestCount()));
		subjectMap.put("totalTime", String.valueOf(subject.getTotalTime()));
		subjectMap.put("totalScore", String.valueOf(subject.getTotalScore()));
		subjectMap.put("status", String.valueOf(subject.getStatus()));
		return subjectMap;
	}
	
	//使用ajax修改
	@ResponseBody
	@RequestMapping(value = "/subjectEdit", method = RequestMethod.POST)
	public Map<String, Object> subjectEdit(@Validated Subject subject, BindingResult result){
		Map<String, Object> messages = new HashMap<String, Object>();
		messages.put("success", false);
		if(result.hasErrors()) {
			return messages;
		}
		try {
			subjectService.editSubject(subject);
			messages.put("success", true);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return messages;
	}
	
	//使用ajax删除
	@ResponseBody
	@RequestMapping(value = "/subjectDelete")
	public Map<String, Object> subjectDelete(@RequestParam Integer subId) throws Exception{
		Map<String, Object> messages = new HashMap<String, Object>();
		messages.put("success", false);
		subjectService.deleteSubject(subId);
		messages.put("success", true);
		return messages;
	}
	
	//使用ajax修改考试状态
	@ResponseBody
	@RequestMapping(value = "/editStatus")
	public Map<String, Object> editStatus(@RequestParam(name = "subId") Integer subId, @RequestParam(name = "statusValue") Integer status) throws Exception{
		Map<String, Object> messages = new HashMap<String, Object>();
		messages.put("success",false);
		Subject subject = subjectService.findSubjectById(subId);
		subject.setStatus(status);
		subjectService.editSubject(subject);
		messages.put("success",true);
		return messages;
	}
	
	//使用ajax杳找全部学生信息和与科目关联的全部学生信息
	@ResponseBody
	@RequestMapping(value = "/getAllUserAndSubjectUser")
	public Map<String, Object> getAllUserAndSubjectUser(@RequestParam Integer subjectId) throws Exception{
		Map<String, Object> list = new HashMap<String, Object>();
		List<User> userList = subjectService.getAllUser();
		List<String> userIdList =  subjectService.getSubjectUser(subjectId);
		List<UserVO> userVOList = new ArrayList<UserVO>();
		for(User user : userList) {
			//只返回角色为学生的信息
			for(ExamUserRole examUserRole : user.getExamUserRole()) {
				if(examUserRole.getExamRole().getRoleId() != 1) {
					continue;
				}else {
					UserVO userVO = new UserVO();
					userVO.setId(user.getId());
					userVO.setName(user.getName());
					userVOList.add(userVO);
				}
			}
			
		}
		list.put("allUser", userVOList);
		list.put("selectedUser", userIdList);
		return list;
	}
	
	//保存修改科目关联信息的学生
	@ResponseBody
	@RequestMapping(value = "/saveSubjectUser")
	public Map<String, Object> saveSubjectUser(@RequestParam(name = "checkedSubjectUser") String[] checkedSubjectUser, 
			@RequestParam(name = "subjectId") Integer subjectId) throws Exception{
		Map<String, Object> messages = new HashMap<String, Object>();
		List<String> checkedUserId = new ArrayList<String>();
		messages.put("success", false);
		for(String str : checkedSubjectUser) {
			checkedUserId.add(str);
		}
		try {
			subjectService.saveSubjectUser(checkedUserId, subjectId);
			messages.put("success", true);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return messages;
	}
	
}
